package com.smartcruise.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.smartcruise.R;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.network.netUtils.NetCollection;

import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/2/4 0004
 * APP全局服务 主要执行的任务有:
 * 1.开启定位 在APP的全局声明周期内收集用户的位置信息并上传 如果上传失败 则存储到本地
 */

public class MainService extends Service implements LocationManager.OnLocationChange {

    private Realm realm;

    private MainBinder mainBinder = new MainBinder();

    private Notification.Builder builder;
    private Notification notification;
    public static final int NotificationId = 1;

    private AMapLocation lastLocation;
    private long lastUploadTime;//记录最近一次上传位置的时间
    private UpLoadLocationManager upLoadLocationManager;
    private CruiseThread cruiseThread;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        builder = new Notification.Builder(getApplicationContext());
        builder.setContentTitle(getString(R.string.app_name))
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示
                .setOngoing(true)//true，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setSmallIcon(R.mipmap.ic_launcher);
        notification = builder.build();

        realm = Realm.getDefaultInstance();
        //初始化定位系统
        LocationManager.getInstance().init(getApplicationContext());
        LocationManager.getInstance().startLocating();
        LocationManager.getInstance().registerObserver(this);
        //初始化位置信息上传系统
        upLoadLocationManager = UpLoadLocationManager.getInstance();
        //初始化本地数据轮询线程
        cruiseThread = new CruiseThread();
        //初始化全局handler
        TimerHandler.getInstance();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        start();
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        start();
        return mainBinder;
    }

    private void start() {
        startForeground(NotificationId, notification);
        upLoadLocationManager.start();
        if (!cruiseThread.isAlive()) {
            cruiseThread.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        LocationManager.getInstance().endLocating();
        LocationManager.getInstance().removeObserver(this);
        realm.close();
        upLoadLocationManager.destroy();
        cruiseThread.interrupt();
        Log.d("MainService", "onDestroy");
    }

    private void refreshNotificationContent(String text) {
        builder.setContentText(text);
        startForeground(NotificationId, builder.build());
    }

    @Override
    public void onChange(AMapLocation aMapLocation) {
        if (isLocationValid(aMapLocation)) {
            lastLocation = aMapLocation;
            lastUploadTime = TimeUtils.currentTime();
            upLoadLocation(aMapLocation);
        }
    }

    /**
     * description:判断当前的位置是否有效 当本次位置与上次位置变化不大的时候 视为无效 不进行上传操作
     */

    private boolean isLocationValid(AMapLocation aMapLocation) {
        if (aMapLocation == null) {//如果当前位置为null  则无效
            return false;
        }

        if (lastLocation == null) {//如果上一次的位置为null 则这是第一个位置 要上传
            return true;
        }

        if (TimeUtils.currentTime() - lastUploadTime > LocationManager.default_interval) {
            Log.d("MainService", "达到必须上传的时间");
            return true;
        }

        double distance = LocationManager.getDistance(aMapLocation.getLatitude(), aMapLocation.getLongitude(),
                lastLocation.getLatitude(), lastLocation.getLongitude());
        return distance >= LocationManager.minDistance;
    }

    /**
     * description:上传位置信息
     */

    private void upLoadLocation(final AMapLocation aMapLocation) {
//        NetCollection.pushLocation(String.valueOf(aMapLocation.getLongitude()), String.valueOf(aMapLocation.getLatitude()), new BaseCallBack() {
//            @Override
//            public void onSuccess(Result result) {
//            }
//
//            @Override
//            public void onFail(Result result) {
//                saveLocation(aMapLocation);
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                saveLocation(aMapLocation);
//                e.printStackTrace();
//            }
//        });
        NetCollection.pushLocation(String.valueOf(aMapLocation.getLatitude()), String.valueOf(aMapLocation.getLongitude()));
    }

//    /**
//     * description:将一个位置信息存储到本地
//     */
//
//    private void saveLocation(final AMapLocation aMapLocation) {
//        try (Realm realm = Realm.getDefaultInstance()) {
//            realm.executeTransactionAsync(new Realm.Transaction() {
//                @Override
//                public void execute(Realm realm) {
//                    SavedLocation savedLocation = realm.createObject(SavedLocation.class);
//                    savedLocation.setEmployeeUserId(TempleUser.getInstance().getAccount());
//                    savedLocation.setLatitude(String.valueOf(aMapLocation.getLatitude()));
//                    savedLocation.setLongitude(String.valueOf(aMapLocation.getLongitude()));
//                    savedLocation.setTime(System.currentTimeMillis());
//                }
//            });
//        }
//    }

    public class MainBinder extends Binder {

        public MainService getService() {
            return MainService.this;
        }

    }

}
